﻿using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DevelopTool.Forms.SystemToolForms
{
    /// <summary>
    /// 端口扫描
    /// </summary>
    public partial class ScanPortForm : BaseUIPage
    {
        /// <summary>
        /// 结果
        /// </summary>
        private DataTable resultTable;

        /// <summary>
        /// DataGridView列信息集合
        /// </summary>
        private List<DataGridColumn> dataGridColumns = new List<DataGridColumn>()
              {
                { new DataGridColumn("ProcessIcon"){ColumnText="图标",Width=-1}},
                 { new DataGridColumn("ProcessId"){ColumnText="进程ID",Width=-1,ColumnType=ColumnType.DefaultFilter}},
                 { new DataGridColumn("ProcessName"){ColumnText="进程名",Width=0,ColumnType = ColumnType.DefaultFilter|ColumnType.RowMain}},
                { new DataGridColumn("Protocol"){ColumnText="协议",Width=-1}},
                { new DataGridColumn("LocalAddress"){ColumnText="本机地址",Width=120,ColumnType=ColumnType.DefaultFilter}},
                { new DataGridColumn("LocalPort"){ColumnText="本机端口",Width=-1,ColumnType=ColumnType.DefaultFilter}},
                { new DataGridColumn("RemoteAddress"){ColumnText="远程地址",Width=120,ColumnType=ColumnType.DefaultFilter}},
                 { new DataGridColumn("RemotePort"){ColumnText="远程端口",Width=-1,ColumnType=ColumnType.DefaultFilter}},
                { new DataGridColumn("State"){ColumnText="状态",Width=100}},               
                { new DataGridColumn("StartTime"){ColumnText="启动时间",Width=140,ColumnType = ColumnType.DefaultFilter}},
                { new DataGridColumn("MainWindowTitle"){ColumnText="窗口标题",Width=0,ColumnType = ColumnType.DefaultFilter}},                
                { new DataGridColumn("ProcessPath"){ColumnText="进程路径",Width=-1}},
              };

        public ScanPortForm()
        {
            InitializeComponent();
        }

        private void ScanPortForm_Load(object sender, EventArgs e)
        {
            //初始化DataTable
            resultTable = new DataTable("ResultTable");
            resultTable.Columns.Add("ProcessIcon", typeof(Icon));
            resultTable.Columns.Add("Protocol", typeof(string));
            resultTable.Columns.Add("LocalAddress", typeof(string));
            resultTable.Columns.Add("LocalPort", typeof(int));
            resultTable.Columns.Add("RemoteAddress", typeof(string));
            resultTable.Columns.Add("RemotePort", typeof(int));
            resultTable.Columns.Add("State", typeof(string));
            resultTable.Columns.Add("ProcessId", typeof(int));
            resultTable.Columns.Add("StartTime", typeof(string));
            resultTable.Columns.Add("MainWindowTitle", typeof(string));
            resultTable.Columns.Add("ProcessName", typeof(string));
            resultTable.Columns.Add("ProcessPath", typeof(string));

            this.dataDisplayControl.BindData(resultTable, this.dataGridColumns, "LocalPort ASC");

            this.dataDisplayControl.BindContextMenuStrip(this.ContextMenuStripDgv);

            this.cboCommand.SelectedIndex = 0;
        }

        /// <summary>
        /// 扫描端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScanPort_Click(object sender, EventArgs e)
        {
            this.btnScanPort.Enabled = false;
            this.ScanPort();
            this.btnScanPort.Enabled = true;

        }

        private void ScanPort()
        {
            resultTable.Clear();
            List<PortInfo> portInfos = new List<PortInfo>();

            LoadingHelper.ShowLoading("正在扫描端口",() =>
            {
                portInfos = PortHelper.GetAllConnections();
            });

            foreach (PortInfo portInfo in portInfos)
            {
                DataRow dataRow = resultTable.NewRow();

                dataRow["ProcessIcon"] = IconHelper.GetFileIcon(portInfo.ProcessPath);
                dataRow["Protocol"] = portInfo.Protocol;
                dataRow["LocalAddress"] = portInfo.LocalAddress;
                dataRow["LocalPort"] = portInfo.LocalPort;
                dataRow["RemoteAddress"] = portInfo.RemoteAddress;
                dataRow["RemotePort"] = portInfo.RemotePort;
                dataRow["State"] = portInfo.State;
                dataRow["ProcessId"] = portInfo.ProcessId;
                dataRow["StartTime"] = portInfo.StartTime;
                dataRow["MainWindowTitle"] = portInfo.MainWindowTitle;
                dataRow["ProcessName"] = portInfo.ProcessName;
                dataRow["ProcessPath"] = portInfo.ProcessPath;

                resultTable.Rows.Add(dataRow);
            }
        }


        /// <summary>
        /// 结束进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnKillProcess_Click(object sender, EventArgs e)
        {
            this.KillProcess();
        }

        private void KillProcess()
        {
            if (this.dataDisplayControl.SelectedRowDic.Count <= 0)
            {
                this.ShowWarningNotifier("请先选择一个需要结束的进程");
                return;
            }
            try
            {

                int processId = this.dataDisplayControl.SelectedRowDic["ProcessId"].ToInt();
                string processName = this.dataDisplayControl.SelectedRowDic["ProcessName"];
                string mainWindowTitle = this.dataDisplayControl.SelectedRowDic["MainWindowTitle"];

                if (!this.ShowAskDialog($"{GlobalData.AppName_zh}-敏感操作", $"是否确定结束 ProcessId:{processId}，{processName}，{mainWindowTitle}", UIStyle.Orange)) return;

                try
                {
                    WindowsHelper.KillProcessById(processId);
                }
                catch (Exception ex)
                {
                    this.ShowErrorDialog(ex.Message);
                }

                this.ScanPort();
                this.ShowSuccessNotifier("已结束进程：" + processName);
            }
            catch (Exception ex)
            {
                this.ShowErrorDialog("进程结束失败：" + ex.ToString());
            }
        }


        private void dataDisplayControl_DataReLoad(object sender, EventArgs e)
        {
            this.ScanPort();
        }

        private void 结束进程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.KillProcess();
        }

        private void 打开路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string processPath = this.dataDisplayControl.SelectedRowDic["ProcessPath"];

                Dialogs.OpenDir(processPath);

            }
            catch (Exception ex)
            {
                this.ShowErrorNotifier("打开路径失败：" + ex.ToString());
            }
        }

        private void 复制完整路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string processPath = this.dataDisplayControl.SelectedRowDic["ProcessPath"];

                Clipboard.SetText(processPath);
                this.ShowSuccessTip("复制成功");
            }
            catch (Exception ex)
            {
                this.ShowErrorNotifier("复制路径失败：" + ex.ToString());
            }
        }

        private void 属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string processPath = this.dataDisplayControl.SelectedRowDic["ProcessPath"];

                FileHelper.ShowFileProperties(processPath);
            }
            catch (Exception ex)
            {
                this.ShowErrorNotifier("打开属性失败：" + ex.ToString());
            }
        }


        /// <summary>
        /// 执行调试命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExecute_Click(object sender, EventArgs e)
        {
            this.codeEditorControl.ClearContent();
            if (string.IsNullOrEmpty(this.txtCommandText.Text)) return;

            this.btnExecute.Enabled = false;
            this.codeEditorControl.ContentText = SystemEx.RunDosCmd(this.txtCommandText.Text);
            this.btnExecute.Enabled = true;
        }


        private void cboCommand_SelectedIndexChanged(object sender, EventArgs e)
        {

            switch (this.cboCommand.SelectedIndex)
            {
                case 0:
                    txtCommandText.Text = "netstat -ano";
                    break;
                case 1:
                    txtCommandText.Text = "netstat -r";
                    break;
                case 2:
                    txtCommandText.Text = "netstat -tan";
                    break;
                case 3:
                    txtCommandText.Text = "netstat -anob";
                    break;
                case 4:
                    txtCommandText.Text = "netstat -ano|find \"\"";
                    break;
                case 5:
                    txtCommandText.Text = "taskkill /pid \"\" /f";
                    break;
                case 6:
                    txtCommandText.Text = "tasklist |find \"\"";
                    break;
                default:
                    txtCommandText.Text = string.Empty;
                    break;
            }

        }
    }
}
